package com.kb.erp.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.kb.erp.entity.file.*;
import com.kb.erp.service.FileHandleService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class FileHandleServiceImpl implements FileHandleService {

    //读取表头
    @Override
    public ResultVO PreUpload(MultipartFile bom, MultipartFile location) throws Exception {
        ResultVO result = new ResultVO();
        result.setStatus(0);
        result.setMsg("");

        ResultItem item = new ResultItem();


        //处理位置文件

        if (location != null) {
            String locationFileName = location.getOriginalFilename();
            if (locationFileName != null) {

                List<String> tem = new ArrayList<>();
                //处理excel格式
                if (locationFileName.endsWith(".xlsx") || locationFileName.endsWith(".xls")) {
                    Workbook workbook = WorkbookFactory.create(location.getInputStream());
                    Sheet sheet = workbook.getSheetAt(0);
                    Row haeder = sheet.getRow(0);
                    for (Cell cell : haeder) {
                        tem.add(cell.getStringCellValue());
                    }

                    item.setSelectLocationValue(tem);
                } else {
                    throw new Exception("坐标文件仅支持xlsx,xls格式");
                }
            }

        }

        if (bom != null) {
            String fileName = bom.getOriginalFilename();
            if (fileName != null) {
                List<String> tem = new ArrayList<>();
                // 处理excel格式
                if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
                    try (InputStream inputStream = bom.getInputStream()) {
                        // 读取 "整理" sheet 的表头
                        boolean headerFound = EasyExcel.read(inputStream)
                                .sheet("整理")
                                .headRowNumber(1) // 只读取第一行作为表头
                                .registerReadListener(new AnalysisEventListener<Map<Integer, String>>() {
                                    @Override
                                    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
                                        for (ReadCellData<?> value : headMap.values()) {
                                            tem.add(value.getStringValue());
                                        }
                                    }

                                    @Override
                                    public void invoke(Map<Integer, String> data, AnalysisContext context) {
                                        // 不处理数据行
                                    }

                                    @Override
                                    public void doAfterAllAnalysed(AnalysisContext context) {
                                        // 数据读取完成后的操作
                                    }
                                }).doReadSync() != null;

                        if (!headerFound) {
                            // 如果 "整理" sheet 不存在，读取 "工程整理" sheet 的表头
                            headerFound = EasyExcel.read(inputStream)
                                    .sheet("工程整理")
                                    .headRowNumber(1)
                                    .registerReadListener(new AnalysisEventListener<Map<Integer, String>>() {
                                        @Override
                                        public void invokeHead(Map<Integer, com.alibaba.excel.metadata.data.ReadCellData<?>> headMap, AnalysisContext context) {
                                            for (ReadCellData<?> value : headMap.values()) {
                                                tem.add(value.getStringValue());
                                            }
                                        }

                                        @Override
                                        public void invoke(Map<Integer, String> data, AnalysisContext context) {
                                            // 不处理数据行
                                        }

                                        @Override
                                        public void doAfterAllAnalysed(AnalysisContext context) {
                                            // 数据读取完成后的操作
                                        }
                                    }).doReadSync() != null;
                        }

                        // 设置 selectValue
                        if (headerFound) {
                            item.setSelectValue(tem);
                        }
                    } catch (IOException e) {
                        e.printStackTrace(); // 处理异常
                    }
                }
            }
        }




        result.setData(item);
        return result;

    }


    @Override
    public ResultVO upload(MultipartFile bom, MultipartFile location, String locationNumber, String meterialCode
            , String specificationDescription
            , String model
            , String number, String RefDes
            , String PartDecal
            , String Layer
            , String Orient
            , String X, String Y, String encapsulationValue) throws Exception {

        //获取bom文件
        List<BomFile> list = new ArrayList<>();
        //获取位置位号
        List<LocationFile> list2 = new ArrayList<>();

        if (location != null) {
            String locationFileName = location.getOriginalFilename();
            if (locationFileName != null) {

                //处理excel格式
                if (locationFileName.endsWith(".xlsx") || locationFileName.endsWith(".xls")) {
                    Map<String, Object> maps = new HashMap<>();

                    maps.put("locationNumber", RefDes);

                    maps.put("partDecalValue", PartDecal);

                    maps.put("layerValue", Layer);

                    maps.put("orientValue", Orient);

                    maps.put("xValue", X);


                    maps.put("yValue", Y);


//反射去找到对应的列
                    changeLocationAnnotation(maps);


                    EasyExcel.read(location.getInputStream(), LocationFile.class, new PageReadListener<LocationFile>(dataList -> {
                        for (LocationFile demoData : dataList) {
                            //将JSON对象转换成实体类
                            LocationFile entity = JSONObject.parseObject(JSONObject.toJSONString(demoData), LocationFile.class);
                            list2.add(entity);
                        }
                    })).sheet(0).doRead();

                    EasyExcel.read(location.getInputStream(), LocationFile.class, new PageReadListener<LocationFile>(dataList -> {
                        for (LocationFile demoData : dataList) {
                            //将JSON对象转换成实体类
                            LocationFile entity = JSONObject.parseObject(JSONObject.toJSONString(demoData), LocationFile.class);
                            list2.add(entity);
                        }
                    })).sheet(1).doRead();
                } else {
                    throw new Exception("坐标文件仅支持xlsx,xls格式");
                }
            }
        }


        if (bom != null) {
            String fileName = bom.getOriginalFilename();
            if (fileName != null) {

                //处理excel格式
                if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
                    Map<String, Object> maps = new HashMap<>();

                    maps.put("locationNumberValue", locationNumber);

                    maps.put("meterialCodeValue", meterialCode);

                    maps.put("modelValue", model);

                    maps.put("consumptionValue", number);

                    maps.put("specificationsValue", specificationDescription);

                    maps.put("encapsulationValue", encapsulationValue);

//反射去找到对应的列
                    changeAnnotation(maps);

                    try {
                        EasyExcel.read(bom.getInputStream(), BomFile.class, new PageReadListener<BomFile>(dataList -> {
                            for (BomFile demoData : dataList) {
                                //将JSON对象转换成实体类
                                BomFile entity = JSONObject.parseObject(JSONObject.toJSONString(demoData), BomFile.class);
                                list.add(entity);
                            }
                        })).sheet("整理").doRead();
                    } catch (NullPointerException e) {
                        //没读到sheet,不抛出异常
//                        throw new RuntimeException(e);
                    }

                    try {
                        EasyExcel.read(bom.getInputStream(), BomFile.class, new PageReadListener<BomFile>(dataList -> {
                            for (BomFile demoData : dataList) {
                                //将JSON对象转换成实体类
                                BomFile entity = JSONObject.parseObject(JSONObject.toJSONString(demoData), BomFile.class);
                                list.add(entity);
                            }
                        })).sheet("工程整理").doRead();
                    } catch (NullPointerException e) {
                        //没读到sheet,不抛出异常
//                        throw new RuntimeException(e);
                    }
                }

                //处理txt格式
                else if (fileName.endsWith(".txt")) {

                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(bom.getInputStream()))) {
                        // Read the header line
                        String headerLine = reader.readLine();
                        while (StringUtils.isBlank(headerLine)) {
                            headerLine = reader.readLine();
                        }

                        if (headerLine != null) {
                            String[] headers = headerLine.split("\\s+"); // Split header by comma

                            // Map headers to their respective indexes
                            Map<String, Integer> headerMap = new HashMap<>();
                            for (int i = 0; i < headers.length; i++) {
                                headerMap.put(headers[i].trim(), i);
                            }

                            // Read data lines
                            String line;

                            Boolean loc = false;
                            if (headerMap.get(locationNumber) != null) {
                                loc = true;
                            }
                            Boolean met = false;
                            if (headerMap.get(meterialCode) != null) {
                                met = true;
                            }
                            Boolean mod = false;
                            if (headerMap.get(model) != null) {
                                mod = true;
                            }
                            Boolean num = false;
                            if (headerMap.get(number) != null) {
                                num = true;
                            }
                            Boolean spe = false;
                            if (headerMap.get(specificationDescription) != null) {
                                spe = true;
                            }

                            Boolean enc = false;
                            if (headerMap.get(encapsulationValue) != null) {
                                enc = true;
                            }


                            while ((line = reader.readLine()) != null) {
                                // Use regular expression to split line by one or more spaces followed by a comma
                                List<String> parts = new ArrayList<>();
// 定义正则表达式来匹配可能带引号的字符串
                                String regex = "\"([^\"]*)\"|([^\\s]+)";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(line);

                                while (matcher.find()) {
                                    if (matcher.group(1) != null) {
                                        // 找到带引号的字符串，去除引号并加入列表
                                        parts.add(matcher.group(1));
                                    } else {
                                        // 没有引号的部分，直接加入列表
                                        parts.add(matcher.group(2));
                                    }
                                }

                                if (parts.size() == headers.length) {
                                    BomFile tem = new BomFile();
                                    if (loc) {
                                        String locationNumberValue = parts.get(headerMap.get(locationNumber)).trim();
                                        tem.setLocationNumberValue(locationNumberValue);// Ensure correct number of fields
                                    }

                                    if (met) {
                                        String meterialCodeValue = parts.get(headerMap.get(meterialCode)).trim();
                                        tem.setMeterialCodeValue(meterialCodeValue);// Ensure correct number of fields
                                    }


                                    if (mod) {
                                        String modelValue = parts.get(headerMap.get(model)).trim();
                                        tem.setModelValue(modelValue);// Ensure correct number of fields
                                    }


                                    if (num) {
                                        String consumptionValue = parts.get(headerMap.get(number)).trim();
                                        tem.setConsumptionValue(Integer.valueOf(consumptionValue));// Ensure correct number of fields
                                    }

                                    if (spe) {

                                        String specificationsValue = parts.get(headerMap.get(specificationDescription)).trim();
                                        tem.setSpecificationsValue(specificationsValue);// Ensure correct number of fields
                                    }

                                    if (enc) {
                                        tem.setEncapsulationValue(parts.get(headerMap.get(encapsulationValue)).trim());// Ensure correct number of fields
                                    }


                                    tem.setId(String.valueOf(UUID.randomUUID()));

                                    list.add(tem);
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace(); // Handle the exception appropriately, e.g., logging or rethrowing
                    }


                } else {
                    throw new Exception("bom文件仅支持xlsx,xls,txt格式");
                }
            }
        }


        List<BomFile> bomFiles = list;
        //todo 不知道去不去掉
//        去掉第一行，因为没有意义
//        if(bomFiles.size()>1){
//           bomFiles = bomFiles.subList(1, list.size());
//        }


        modifyLocationNumbers(bomFiles);


        return handle(bomFiles, list2);
    }


    public ResultVO handle(List<BomFile> bomFiles, List<LocationFile> list2) {


        for (BomFile tem : bomFiles) {
            tem.setId(String.valueOf(UUID.randomUUID()));
            tem.setDefalutValue("");
        }

        for (LocationFile tem : list2) {
            tem.setId(String.valueOf(UUID.randomUUID()));

        }

        List<BomFile> temList = bomFiles.stream().filter(product -> product != null && StringUtils.isNotBlank(product.getMeterialCodeValue())).collect(Collectors.toList());
        // a. 获取bom文件中物料重复的值
        HashSet<String> meterialSet = new HashSet<>();

        for (BomFile bomFile : temList) {
            boolean add = meterialSet.add(bomFile.getMeterialCodeValue());
            if (!add) {
                if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                    bomFile.setDefalutValue(bomFile.getDefalutValue() + " bom文件中,料号重复:" + bomFile.getMeterialCodeValue());
                } else {
                    bomFile.setDefalutValue("bom文件中,料号重复:" + bomFile.getMeterialCodeValue());
                }

            }


        }
//        Map<String, Long> materialCounts = temList.stream()
//                .collect(Collectors.groupingBy(BomFile::getMeterialCodeValue, Collectors.counting()));
//
//
//
//        materialCounts.entrySet().stream()
//                .filter(entry -> entry.getValue() > 1)
//                .forEach(entry -> {
//                    String materialCode = entry.getKey();
////                    List<String> products = finalBomFiles.stream()
////                            .filter(bom -> bom.getMeterialCode().equals(materialCode))
////                            .map(BomFile::getProduct)
////                            .collect(Collectors.toList());
//
//                    Result result = new Result();
//                    result.setSource("bom文件中,料号重复");
//                    result.setId(String.valueOf(UUID.randomUUID()));
////                    result.setCode(products.toString());
//                    result.setValue(materialCode);
//                    results.add(result);
//                });
        List<LocationFile> list2Tem = list2.stream().filter(product -> product != null && StringUtils.isNotBlank(product.getLocationNumber())).collect(Collectors.toList());
        // b. 获取位置文件中locationNumber重复的值,弃用
//        Map<String, Long> locationCounts = list2Tem.stream()
//                .collect(Collectors.groupingBy(LocationFile::getLocationNumber, Collectors.counting()));
//
//        locationCounts.entrySet().stream()
//                .filter(entry -> entry.getValue() > 1)
//                .forEach(entry -> {
//                    Result result = new Result();
//                    result.setId(String.valueOf(UUID.randomUUID()));
//                    result.setSource("坐标文件中,位号重复");
//                    result.setCode("");
//                    result.setValue(entry.getKey());
//                    results.add(result);
//                });


        //c.获取bom文件中位号重复的值
        //抛弃掉位号为null的数据
        List<BomFile> bomFilesTem = bomFiles.stream().filter(product -> product != null && product.getConsumptionValue()!=null).collect(Collectors.toList());


        meterialSet = new HashSet<>();

        for (BomFile bomFile : bomFilesTem) {
            if(StringUtils.isBlank(bomFile.getLocationNumberValue())){
                continue;
            }
            List<String> stream = Arrays.asList(bomFile.getLocationNumberValue().split("\\s+"));

            List<String> resultTem = new ArrayList<>();

            for (String locTem : stream) {
                boolean add = meterialSet.add(locTem);
                if (!add) {
                    resultTem.add(locTem);

                }
            }
            if (resultTem.size() > 0) {
                if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                    bomFile.setDefalutValue(bomFile.getDefalutValue() + " bom文件中,位号重复:" + resultTem.stream().collect(Collectors.joining(",")));
                } else {
                    bomFile.setDefalutValue("bom文件中,位号重复:" + resultTem.stream().collect(Collectors.joining(",")));
                }
            }


        }


//// 获取locationNumber字段重复的值
//        Map<String, List<String>> bomLocationCounts = bomFilesTem.stream()
//                .flatMap(bom -> Arrays.stream(bom.getLocationNumberValue().split("\\s+"))
//                        .map(location -> new AbstractMap.SimpleEntry<>(location, bom.getId())))
//                .collect(Collectors.groupingBy(Map.Entry::getKey,
//                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
//
//// 遍历重复的locationNumber，并添加到results中
//        bomLocationCounts.entrySet().stream()
//                .filter(entry -> entry.getValue().size() > 1)
//                .forEach(entry -> {
//                    String locationNumber = entry.getKey();
//                    List<String> products = entry.getValue();
//
//                    Result result = new Result();
//                    result.setSource("bom文件中,位号重复");
//                    result.setId(String.valueOf(UUID.randomUUID()));
//                    result.setCode(products.toString());
//                    result.setValue(locationNumber);
//                    results.add(result);
//                });


        //d.获取bom位号不在位置文件的值
        // Assuming results is a List<Result> initialized somewhere in your code

// Map to store Results by product
        Map<String, Result> resultMap = new HashMap<>();
        if (list2Tem != null && list2Tem.size() > 0) {

            for (BomFile bomFile : bomFilesTem) {
                // Initialize a StringBuilder to collect bomNumbers
                StringBuilder missingBomNumbers = new StringBuilder();
                boolean foundAtLeastOne = false;

                if(StringUtils.isNotBlank(bomFile.getLocationNumberValue())){
                    String[] bomNumbers2 = bomFile.getLocationNumberValue().split(" ");

                    if(bomNumbers2!=null) {
                        List<String> nonEmptyList = Arrays.stream(bomNumbers2)
                                .filter(str -> !str.isEmpty())
                                .collect(Collectors.toList());

                        for (String bomNumber : nonEmptyList) {
                            boolean found = false;

                            for (LocationFile locationFile : list2Tem) {
                                if (bomNumber.equals(locationFile.getLocationNumber())) {
                                    found = true;
                                    break;
                                }
                                if (found) {
                                    foundAtLeastOne = true;
                                    break;
                                }
                            }

                            if (!found) {
                                missingBomNumbers.append(bomNumber).append(",");
                            }
                        }
                        // If any bomNumbers were missing, create a Result object
                        if (!foundAtLeastOne && missingBomNumbers.length() > 0) {
                            String product = bomFile.getId();
                            String missingNumbers = missingBomNumbers.substring(0, missingBomNumbers.length() - 1); // Remove trailing comma
                            Result result = resultMap.get(product);

                            //跳过pcb判断
                            if (!missingNumbers.equals("PCB")) {
                                if (result == null) {
                                    result = new Result("bom文件中的位号在坐标文件中缺失", product, missingNumbers);

                                    result.setId(String.valueOf(UUID.randomUUID()));
                                    resultMap.put(product, result);

                                    if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                                        bomFile.setDefalutValue(bomFile.getDefalutValue() + " bom文件中的位号在坐标文件中缺失:" + missingNumbers);
                                    } else {
                                        bomFile.setDefalutValue("bom文件中的位号在坐标文件中缺失:" + missingNumbers);
                                    }


                                } else {
                                    result.setId(String.valueOf(UUID.randomUUID()));
                                    result.setValue(result.getValue() + "," + missingNumbers);
                                }
                            }


                        }

                    }

                }



            }

// Add all collected results to the results list
//            results.addAll(resultMap.values());
        }



        //e.数量与位号数量不匹配

        for (BomFile bomFile : bomFilesTem) {

            if(StringUtils.isBlank(bomFile.getLocationNumberValue())&&bomFile.getConsumptionValue()!=0){

                    if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                        bomFile.setDefalutValue(bomFile.getDefalutValue() + " 数量与位号数量不匹配,数量为:" + bomFile.getConsumptionValue() + ",位号数量为:0");
                    } else {
                        bomFile.setDefalutValue("数量与位号数量不匹配,数量为:" + bomFile.getConsumptionValue() + ",位号数量为:0" );
                    }
                    continue;
                }



            String[] consumptions = bomFile.getLocationNumberValue().split(" ");

            if(consumptions!=null){
                List<String> nonEmptyList = Arrays.stream(consumptions)
                        .filter(str -> !str.isEmpty())
                        .collect(Collectors.toList());

                if (bomFile.getConsumptionValue() != null) {
                    if (nonEmptyList.size() != bomFile.getConsumptionValue()) {
                        if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                            bomFile.setDefalutValue(bomFile.getDefalutValue() + " 数量与位号数量不匹配,数量为:" + bomFile.getConsumptionValue() + ",位号数量为:"+nonEmptyList.size());
                        } else {
                            bomFile.setDefalutValue("数量与位号数量不匹配,数量为:" + bomFile.getConsumptionValue() + ",位号数量为:" + nonEmptyList.size());
                        }
                    }
                }
            }


        }


        // f. 获取bom文件中型号

        //抛弃掉型号为null的数据
        List<BomFile> bomFilesTem2 = bomFiles.stream().filter(product -> product != null && StringUtils.isNotBlank(product.getModelValue())).collect(Collectors.toList());

        meterialSet = new HashSet<>();

        for (BomFile bomFile : bomFilesTem2) {
            boolean add = meterialSet.add(bomFile.getModelValue());
            if (!add) {
                if (StringUtils.isNotBlank(bomFile.getDefalutValue())) {
                    bomFile.setDefalutValue(bomFile.getDefalutValue() + " bom文件中,型号重复:" + bomFile.getModelValue());
                } else {
                    bomFile.setDefalutValue("bom文件中,型号重复:" + bomFile.getModelValue());
                }

            }
        }


//        Map<String, Long> modelCounts = bomFilesTem2.stream()
//                .collect(Collectors.groupingBy(BomFile::getModelValue, Collectors.counting()));
//
//
//        modelCounts.entrySet().stream()
//                .filter(entry -> entry.getValue() > 1)
//                .forEach(entry -> {
//                    String model = entry.getKey();
////                    List<String> products = bomFilesTem2.stream()
////                            .filter(bom -> bom.getModel().equals(model))
////                            .map(BomFile::getProduct)
////                            .collect(Collectors.toList());
//
//                    Result result = new Result();
//                    result.setSource("bom文件中,型号重复");
//                    result.setId(String.valueOf(UUID.randomUUID()));
////                    result.setCode(products.toString());
//                    result.setValue(model);
//                    results.add(result);
//                });


        ResultVO volist = new ResultVO();

        volist.setStatus(0);
        volist.setMsg("");


        ResultItem item = new ResultItem();


        bomFiles = bomFiles.stream().sorted(Comparator.comparing(BomFile::getDefalutValue).reversed()).collect(Collectors.toList());


        item.setBomList(bomFiles);
        item.setLocationList(list2);

        volist.setData(item);


        return volist;
    }


    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }


    public static void modifyLocationNumbers(List<BomFile> bomFiles) {
        for (BomFile bomFile : bomFiles) {
            String originalLocationNumber = bomFile.getLocationNumberValue();
            String modifiedLocationNumber = processLocationNumber(originalLocationNumber);
            bomFile.setLocationNumberValue(modifiedLocationNumber);
        }
    }


    //处理位号的范围,短斜线
    public static String processLocationNumber(String locationNumber) {

        if (locationNumber == null||StringUtils.isBlank(locationNumber)) {
            return locationNumber;
        }


        String[] split = locationNumber.split(" ");
        StringBuffer result = new StringBuffer();

        for(String tem:split){
            // 匹配模式，例如 "152-154" 或 "abc159-162"
            String regex = "(\\D*)(\\d+)-(\\D*)\\2(\\d+)";

            Pattern pattern = Pattern.compile("([a-zA-Z]+)(\\d+)(?:-([a-zA-Z]+)?(\\d+))?");
            Matcher matcher = pattern.matcher(tem);
             if (matcher.matches()) {
                String prefix1 = matcher.group(1); // 第一个捕获组，第一个前缀
                int start = Integer.parseInt(matcher.group(2));   // 第二个捕获组，起始数字部分
                 // 判断第三个和第四个捕获组是否存在，以确定是 r4-r51 还是 r4-51 的情况
                 String prefix2 = matcher.group(3); // 第三个捕获组，第二个前缀（可能为空）
                 String endGroup = matcher.group(4); // 第四个捕获组，结束数字部分

                 int end;
                 if (endGroup != null) {
                     end = Integer.parseInt(endGroup); // 如果第四个捕获组不为空，则是 r4-r51 的情况
                 } else {
                     end = start; // 如果第四个捕获组为空，则是 r4-51 的情况，结束数字部分与起始数字相同
                 }

                // 将范围拆分为单独的数字
                for (int i = start; i <= end; i++) {
                    result.append(prefix1).append(i).append(" ");

                }
                matcher.appendReplacement(result, "");
                 matcher.appendTail(result);// 替换匹配部分为空字符串
            }
             else{
                 matcher.appendTail(result);
                 result.append(" ");
             }


        }




        return result.toString().trim(); // 返回处理后的位置信息字符串
    }


    public Object changeLocationAnnotation(Map<String, Object> maps) {
        try {
            //这里map的key是实体类字段名，value是需要动态修改的注解值
            Class<?> name = LocationFile.class;
            LocationFile instance = (LocationFile) name.newInstance();
            if (maps.size() > 0) {
                for (String key : maps.keySet()) {
                    Field value = instance.getClass().getDeclaredField(key);
                    value.setAccessible(true);
                    //ExcelProperty 是一个注解注解
                    ExcelProperty apiParam = value.getAnnotation(ExcelProperty.class);
                    InvocationHandler invocationHandler = Proxy.getInvocationHandler(apiParam);
                    Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
                    memberValues.setAccessible(true);
                    Map<String, Object> values = (Map<String, Object>) memberValues.get(invocationHandler);
                    String[] val = (String[]) values.get("value");
//                    System.out.println("------改之前:"+ Arrays.toString(val));
                    if (StringUtils.isNotBlank(maps.get(key).toString())) {
                        values.put("value", new String[]{maps.get(key).toString()});
                    } else {

                        values.put("value", new String[]{key});
                    }
                    //修改属性
//                    System.out.println("-----------------");
                    value.setAccessible(true);
                    ExcelProperty apiParam1 = (ExcelProperty) value.getAnnotation(ExcelProperty.class);

//                    System.out.println("------改之后:"+ Arrays.toString(apiParam1.value()));
                }

            }
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    public Object changeAnnotation(Map<String, Object> maps) {
        try {
            //这里map的key是实体类字段名，value是需要动态修改的注解值
            Class<?> name = BomFile.class;
            BomFile instance = (BomFile) name.newInstance();
            if (maps.size() > 0) {
                for (String key : maps.keySet()) {
                    Field value = instance.getClass().getDeclaredField(key);
                    value.setAccessible(true);
                    //ExcelProperty 是一个注解注解
                    ExcelProperty apiParam = value.getAnnotation(ExcelProperty.class);
                    InvocationHandler invocationHandler = Proxy.getInvocationHandler(apiParam);
                    Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
                    memberValues.setAccessible(true);
                    Map<String, Object> values = (Map<String, Object>) memberValues.get(invocationHandler);
                    String[] val = (String[]) values.get("value");
//                    System.out.println("------改之前:"+ Arrays.toString(val));
                    if (StringUtils.isNotBlank(maps.get(key).toString())) {
                        values.put("value", new String[]{maps.get(key).toString()});
                    } else {

                        values.put("value", new String[]{key});
                    }
                    //修改属性
//                    System.out.println("-----------------");
                    value.setAccessible(true);
                    ExcelProperty apiParam1 = (ExcelProperty) value.getAnnotation(ExcelProperty.class);

//                    System.out.println("------改之后:"+ Arrays.toString(apiParam1.value()));
                }

            }
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
